"use client"
import React, { useEffect } from 'react';
import { Button, Form, Input } from 'antd';
import { useRouter } from 'next/navigation';
import axios from 'axios';
import '../../css/login.css'

function App(params: any) {
  const router = useRouter();

  const onFinish = (values: any) => {
    axios.get("http://localhost:3001/login").then((res) => {
      let flag = res.data.some((v: any) => {
        return v.phone === values.phone && v.password === values.password;
      });
      if (flag) {
        localStorage.setItem('token', values.phone);
        // 使用 setTimeout 确保在状态更新后再进行路由跳转
        setTimeout(() => {
          router.push('/home');
        }, 0);
      }
    });
  };

  useEffect(() => {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      // 使用 setTimeout 确保在状态更新后再进行路由跳转
      setTimeout(() => {
        router.push('/home');
      }, 0);
    }
  }, []);

  return (
    <div className='big'>
      <div className='box'>
        <Form
          name="basic"
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item>
            <h1>登录客户关系管理系统</h1>
          </Form.Item>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[{ required: true, message: '请输入手机号!' },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号格式不正确!',
            }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '密码不能为空!' },
            {
              pattern: /^[a-zA-Z0-9]{6}$/,
              message: "请输入六位密码!",
            }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default App;